// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const { roomId } = event
  
  try {
    // 查找房间
    const room = await db.collection('rooms').where({
      roomId: roomId
    }).get()
    
    if (room.data.length === 0) {
      return {
        success: false,
        error: '房间不存在'
      }
    }
    
    const roomData = room.data[0]
    
    // 检查房间状态
    if (roomData.status !== 'waiting') {
      return {
        success: false,
        error: '房间已开始游戏'
      }
    }
    
    // 检查房间人数
    if (roomData.players.length >= roomData.maxPlayers) {
      return {
        success: false,
        error: '房间已满'
      }
    }
    
    // 检查是否已在房间中
    const isInRoom = roomData.players.some(player => player.openid === wxContext.OPENID)
    if (isInRoom) {
      return {
        success: false,
        error: '你已在房间中'
      }
    }
    
    // 添加玩家到房间
    const newPlayer = {
      openid: wxContext.OPENID,
      nickName: event.nickName,
      avatarUrl: event.avatarUrl,
      isReady: false
    }
    
    await db.collection('rooms').where({
      roomId: roomId
    }).update({
      data: {
        players: db.command.push(newPlayer),
        lastUpdateTime: db.serverDate()
      }
    })
    
    return {
      success: true,
      roomData: {
        ...roomData,
        players: [...roomData.players, newPlayer]
      }
    }
  } catch (error) {
    console.error('加入房间失败:', error)
    return {
      success: false,
      error: error.message
    }
  }
} 